<?php
/**
 * Created by PhpStorm.
 * User: bluer
 * Date: 12/16/15
 * Time: 22:59
 */

class Processor {
    protected $inGroups = array();

    /**
     * Switch the target table if the sublist exists
     *
     * @param Builder $query
     * @param int $userId
     * @return string
     */
    public function switchTable(Builder &$query, $userId) {
        if ( in_array($query->getFrom(), $query->getConnection()->getMultiTables()) && is_numeric($userId) ) {
            return $this->processSublist($query->getFrom(), $userId);
        }

        return $query->getFrom();
    }

    /**
     * 获取分表信息
     *
     * Dependent on USER_AUTH_INFO table
     *
     * @param string $tableName The base table name
     * @param int $userId Optional
     * @return mixed
     */
    public function processSublist($tableName = null, $userId = 0) {
        global $uddb;

        if (is_null($uddb) || is_null($tableName) || empty($tableName))
            return null;

        if (is_numeric($userId) && $userId > 0) {
            return $tableName . '_' . floor($userId / 100000);
        }

        $maxId = $uddb->getVar('SELECT MAX(id) FROM ' . $uddb->userAuthInfo);
        if (!$maxId) return $tableName;

        $list = array();
        $num = floor($maxId / 100000);

        for ($i = 0; $i <= $num; $i++) {
            $list[] = $tableName . '_' . $i;
        }

        return $list;
    }

    /**
     *  处理 " WHERE `user_id` IN(..) " 字句所涉及的分表查询
     *
     * @param Builder $query
     * @param $where
     */
    public function processWhereIn(Builder &$query, $where) {
        extract($where);

        if (!is_array($values) || count($values) == 0) return;

        foreach ($values as $uid) {
            $table = $this->processSublist($query->getFrom(), $uid);
            $this->inGroups[$table][] = $uid;
        }

        foreach ($this->inGroups as $table => $values) {
            $this->inGroups[$table] = compact('type', 'column', 'values', 'operator', 'relation');
        }
    }

    /**
     * 获取 IN 操作的分表分组结果
     *
     * @return array
     */
    public function getInGroups() {
        return $this->inGroups;
    }
}